import { defineComponent, ref, reactive } from "vue";
import Popup from "@/components/Popup/Popup";
import styles from "./Add.module.less";
import to from "await-to-js";
import fetchBase64AsUint8Array from "@/common/utils/fetchBase64AsUint8Array";
import pako from "pako";
import uint8Array2Base64 from "@/common/utils/uint8Array2Base64";
import { message } from "ant-design-vue";
import _ from "lodash";
export default defineComponent({
  props: {
    service: {
      type: Object,
    }
  },
  emits: ["change"],
  setup(props, { expose, emit }) {
    const popupRef = ref(null as any);
    const formRef = ref(null as any);
    const state = reactive({
      type: "add",
      form: {
        id: null,
        content: null as string | null,
        sort: 0,
        status: 1,
        remark: null as string | null,
      },
    })
    const editing = ref(false);
    // 获取详情
    const getDetail = async () => {
      const [err, res]: any = await to(props.service?.detail(state.form.id));
      if (!err) {
        const resultObj = res?.data?.data;
        let events_pako_return = "";
        const content = resultObj.content;
        const uint8Arr = await fetchBase64AsUint8Array(content);
        events_pako_return = new TextDecoder().decode(pako.inflate(uint8Arr));
        events_pako_return = decodeURIComponent(events_pako_return);
        state.form.content = events_pako_return;
        state.form.sort = resultObj?.sort || 0;
        state.form.status = resultObj?.status || 0;
        state.form.remark = resultObj.remark || null;
      }
    }
    const open = async ({ type, id }) => {
      state.type = type;
      state.form.id = id;
      if (type === 'edit') {
        await getDetail();
      }
      popupRef.value.open();
    }
    const getContent = async (jsonStr) => {
      try {
        const json = JSON.parse(jsonStr);
        const contentObjStr = JSON.stringify(json);
        let event = encodeURIComponent(contentObjStr);
        let events_pako = pako.deflate(event);
        let content: any = await uint8Array2Base64(events_pako);
        return [content];
      } catch (err) {
        return [null];
      }
    }
    const submit = async () => {
      formRef.value
        .validate()
        .then(async () => {
          editing.value = true;
          const params = _.cloneDeep(state.form);
          const jsonStr = params.content;
          const [content] = await getContent(jsonStr);
          if (!content) {
            message.error("内容JSON有误,请重新填写!");
            return;
          }
          params.content = content;
          const [err, res]: any = await to((state.type === 'edit' ? props.service?.edit : props.service?.add)(params));
          if (!err) {
            message.success("提交成功!");
            popupRef.value.close();
            emit("change");
          }
          editing.value = false;
        })
    }
    expose({
      open,
    })
    return () => (
      <Popup ref={popupRef} title="重传支体" width="800px" oriState={state} v-slots={{
        footer: () => <>
          <a-button type="primary" onClick={() => { submit() }}>提交</a-button>
          <a-button onClick={() => { popupRef.value.close() }}>关闭</a-button>
        </>
      }}>
        <div class={styles.container}>
          <div class={styles.formBox}>
            <a-form model={state.form} ref={formRef} label-col={{ style: { width: '130px', marginRight: '10px' } }} wrapper-col={{ span: 28 }}>
              <a-form-item required label="内容JSON" name="content">
                <a-textarea styles="" v-model:value={state.form.content} placeholder="请填写内容JSON" />
              </a-form-item>
              <a-form-item label="排序" name="sort">
                <a-input-number min={0} v-model:value={state.form.sort} placeholder="请输入排序" />
              </a-form-item>
              <a-form-item label="是否开启" name="status">
                <a-radio-group
                  v-model:value={state.form.status}
                  name="radioGroup"
                >
                  <a-radio value={0}>是</a-radio>
                  <a-radio value={1}>否</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="备注" name="remark">
                <a-textarea v-model:value={state.form.remark} placeholder="请输入备注" />
              </a-form-item>
            </a-form>
          </div>
        </div>
      </Popup>
    )
  }
})